#pragma once
#include "Log.hpp"
#include "Common.hpp"
#include "IntAddr.hpp"
#include <functional>

const int backlog = 8;

using namespace MyLog;

using func_t = std::function<std::string(const std::string&,InetAddr&)>;

class TcpServer :public Nocopy
{
public:
    TcpServer(uint16_t port,func_t func) : _port(port)
    , _listensockfd(0)
    , _isrunning(false)
    , _func(func)
    {
    }
    void Init()
    {
        _listensockfd = socket(AF_INET, SOCK_STREAM, 0);
        if (_listensockfd < 0)
        {
            LOG(Loglevel::ERROR) << "socket error";
            exit(SOCKET_ERROR);
        }
        LOG(Loglevel::INFO) << "socket success: " ;

        InetAddr local(_port);

        int n = bind(_listensockfd,local.GetNetAddr(),local.GetSocklen());
        if(n<0)
        {
            LOG(Loglevel::ERROR) << "bind error";
            exit(BIND_ERROR);
        }
        LOG(Loglevel::INFO) << "bind success "<<_listensockfd;

        n = listen(_listensockfd,backlog);
        if(n<0)
        {
            LOG(Loglevel::ERROR) <<"listen error";
            exit(LISTEN_ERROR);
        }
        LOG(Loglevel::INFO) << "listen success "<<_listensockfd;

    }



    class ThreadData
    {
        public:
        ThreadData(int fd,InetAddr &peer,TcpServer *ts)
        :sockfd(fd)
        ,addr(peer)
        ,tser(ts)
        {}
        int sockfd;
        InetAddr addr;
        TcpServer *tser;
    };
    void Service(int sockfd,InetAddr &peer)
    {
        while(true)
        {
            char buffer[1024];
            ssize_t n = read(sockfd,buffer,sizeof(buffer));
            if(n>0)
            {
                LOG(Loglevel::DEBUG) << peer.GetString()<<"say: "<<buffer;
                std::string echo_toclient = _func(buffer,peer);
                // echo_toclient += buffer;
                write(sockfd,echo_toclient.c_str(),echo_toclient.size());
            }
            else if(n<0)
            {
                LOG(Loglevel::DEBUG) <<peer.GetString()<< " 读取error";
                close(sockfd);
                break;
            }
            else 
            {
                LOG(Loglevel::DEBUG)<<peer.GetString()<< " 退出了...";
                close(sockfd);
                break;
            }
        }
    }
    static void* Routine(void *args)
    {
        pthread_detach(pthread_self());
        ThreadData *fd = static_cast<ThreadData *>(args);
        fd->tser->Service(fd->sockfd,fd->addr);
        delete fd;
        return nullptr;
    }

    void Run()
    {
        _isrunning = true;
        while(_isrunning)
        {
            struct sockaddr_in peer;
            socklen_t len = sizeof(sockaddr_in);
            int sockfd = accept(_listensockfd,CONV(&peer),&len);
            if(sockfd<0)
            {
                LOG(Loglevel::DEBUG) << "accept error";
                continue;
            }
            InetAddr addr(peer);
            LOG(Loglevel::INFO) <<"accept success, peer addr: "<<addr.GetString();

            ThreadData *td = new ThreadData(sockfd,addr,this);
            pthread_t tid;
            pthread_create(&tid,nullptr,Routine,td);

            // //for test
            // Service(sockfd,addr);

        }
        _isrunning = false;
    }
    ~TcpServer()
    {
    }

private:
    int _listensockfd;
    uint16_t _port;
    func_t _func;
    bool _isrunning;
};